#include "e2d/ui/MaterialEditor.h"
#include "e2d/ui/State.h"
#include "e2d/ui/Utils.h"
#include "e2d/ui/Temps.h"

e2d::MaterialEditor::MaterialEditor()
	:fxcc::imgui::Layer("Material")
{
	LoadLastEditPath();
	LoadDefaultToken();
	Load();

}

void e2d::MaterialEditor::Load()
{
	ModelLoader m_Loader;
	m_Inst = m_Loader.LoadMaterial(m_InstPath);
	if (m_Inst)
	{
		m_Inst->LoadNativeData();
		m_Inst->LoadTextures();
	}
}

void e2d::MaterialEditor::LoadLastEditPath()
{
	m_InstPath = fxcc::FileUtil::ReadFileToString(CH_Path());
}

void e2d::MaterialEditor::LoadDefaultToken()
{
	fxcc::yml::Serializer serializer;
	bool flag = serializer.DecodePath<e2d::EffectToken>(Default_Effect_Path(), DefaultEffectToken());
	if (flag)
	{
		ztclog::info("[ Materlal Editor ] Load the defualt token is %s", DefaultEffectToken().m_Key.c_str());
	}
}



void e2d::MaterialEditor::ViewFunc()
{
	bool editFlag{ 0 };

	if (!m_Inst)
	{
		return;
	}

	auto& io = ImGui::GetIO();

	ImGui::Text("Default Effect");
	m_Editor.EditInst<e2d::EffectToken>("m_DefaultToken", DefaultEffectToken());

	ImGui::Text("Material View");
	ImGui::Text("%s", m_InstPath.c_str());
	bool _MatChanged = m_Editor.EditInst<e2d::MaterialView>("Material View", *m_Inst);

	if (ImGui::IsWindowFocused())
	{
		if (ImGui::IsKeyReleased(ImGuiKey_S) && io.KeyCtrl)
		{
			OnSave();
		}
	}
}

void e2d::MaterialEditor::HandleFunc()
{

	auto& sg = e2d::State::Inst();
	
	if (sg.m_EditMaterialFlag)
	{
		OnSave();

		ztclog::info("[ Materlal Editor ]  Load mat %s", sg.m_EditMaterialPath.c_str());

		m_InstPath = sg.m_EditMaterialPath;
		Load();
		
		sg.m_EditMaterialFlag = false;
	}
}

void e2d::MaterialEditor::OnSave()
{
	fxcc::yml::Serializer serializer;
	bool flag = serializer.EncodePath<e2d::MaterialView>(m_InstPath, *m_Inst);
	ztclog::info("[Materlal Editor ] save the material to %s", m_InstPath.c_str());


}

void e2d::MaterialEditor::OnDestroy()
{
	SaveLastEditPath();
	SaveDefaultToken();
	OnSave();
}

void e2d::MaterialEditor::SaveLastEditPath()
{
	ztclog::info("[ Materlal Editor ] Save path is %s", m_InstPath.c_str());
	fxcc::FileUtil::Write(CH_Path(), m_InstPath);


}

void e2d::MaterialEditor::SaveDefaultToken()
{
	fxcc::yml::Serializer serializer;
	bool flag = serializer.EncodePath<e2d::EffectToken>(Default_Effect_Path(), DefaultEffectToken());
	ztclog::info("[ Materlal Editor ] save the default effect token is %s", DefaultEffectToken().m_Key.c_str());
}

std::string e2d::MaterialEditor::CH_Path()
{
	return ".cache/mat.imgui";
}

std::string e2d::MaterialEditor::Default_Effect_Path()
{
	return ".cache/default_effect.imgui";
}

e2d::EffectToken& e2d::MaterialEditor::DefaultEffectToken()
{
	return ShaderLoader::m_DefaultToken;
}
